/**
 * 
 */
package edu.gtcfla.km.security.realm;

import java.util.Collection;
import java.util.Iterator;
import java.util.Set;

import org.apache.shiro.subject.MutablePrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.vsg.biz.account.Role;
import org.vsg.biz.account.User;
import org.vsg.biz.account.repositories.RoleRepo;

import edu.gtcfla.km.security.RoleStrategyRule;
import edu.gtcfla.km.security.api.AccountPrincipalConstant;

/**
 * @author vison
 *
 */
public class SimpleRoleStrategyRule implements  RoleStrategyRule {

	@Autowired(required=false)		
	private RoleRepo roleRepo;	
	
	/* (non-Javadoc)
	 * @see org.vsg.security.strategy.RoleStrategyRule#findRealyRoleIds(java.lang.String)
	 */
	@Override
	public Set<Role> findActiveRoles(MutablePrincipalCollection principalCollection) {
		// TODO Auto-generated method stub
		Collection<Role> activeRole =principalCollection.fromRealm( RoleStrategyRule.ACCOUNT_ACTIVE_ROLES );
		
		if (activeRole == null  || activeRole.isEmpty() ) {
			// --- find role by account id --
			
			Collection coll = principalCollection.fromRealm( AccountPrincipalConstant.ACCOUNT );
			
			Iterator collIter = coll.iterator();

			if ( collIter.hasNext() ) {
				User user = (User) collIter.next();
				
				activeRole =   roleRepo.findByUserId( user.getId() );
				if (!activeRole.isEmpty()) {
					setRealyRoleIdToPrincipal( activeRole , principalCollection );
				}

			}
			
		}

		return (Set<Role>)activeRole ;
	}


	private void setRealyRoleIdToPrincipal(Collection<Role> roles,
			MutablePrincipalCollection principalCollection) {
		// TODO Auto-generated method stub
		principalCollection.addAll(roles, RoleStrategyRule.ACCOUNT_ACTIVE_ROLES );
	}

	
	
}
